<?php
/*
 * 图像的裁切
 * 
 */


header('content-type:text/html;charset=utf-8');
date_default_timezone_set('UTC');//date时间报错的处理
// header('content-type:image/png,image/gif,image/jpeg');
// $im = imagecreatefrompng('zz.png');
// $result = filetype('zz.png');
// var_dump($result);
//imagepng($im);
// $r = getimagesize('zz.png');

// print_r($r); 

function imagecut($srcpath,$x,$y,$w,$h,$dir)
{
	#判断上传的图像类型
	$imageinfo = getimagesize($srcpath);
	#定义本函数所支持的图像类型
	$allowcutimg = array('image/jpeg','imgae/png','imgae/gif');
	if(in_array($imageinfo['mime'],$allowcutimg))
	{
		return false;
	}
	switch ($imageinfo['mime']) {
		case 'image/jpeg': 
			$src_image = imagecreatefromjpeg($srcpath); 
			$funname = 'imagejpeg';	
			$ext = '.jpeg';
			break;
		case 'image/png':
			$src_image = imagecreatefrompng($srcpath);
			$funname = 'imagepng';
			$ext = '.png';
			break;
		case 'image/gif':
			$src_image = imagecreatefromgif($srcpath);
			$funname = 'imagegif';
			$ext = '.gif';
			break;
	}
	#判断坐标及裁切的宽和高是否合法
	$imagewidth = imagesx($src_image);
	$imageheight = imagesy($src_image);
	if($x<0 || $x>$imagewidth) $x=0;
	if($y<0 || $y>$imageheight) $y=0;
	if($w<0 || $w>$imagewidth)
	{
		$w = $imagewidth;
	} 
	if($h<0 || $h>$imageheight)
	{
		$h = $imageheight;
	}

	#创建目标画布
	$dst_image = imagecreatetruecolor($w,$h);
	#裁切功能
	imagecopy ($dst_image, $src_image,0,0,$x,$y,$w,$h);
	#设置裁切后图像的名称
	$imagename = date('Ymd').rand(0,999).$ext;//同一时间用户访问多的话时间加上秒和随机数加大
	$funname($dst_image,$dir.$imagename);
}
#输出目标结果
imagecut($dst_image);
#模拟调用 裁切生成图的保存至当前文件夹
imagecut('zz.jpeg',10,10,100,100,'./');
?>